package com.eleadin.ruleengine.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtil {
    /**
     * 校验token是否正确
     * @param token
     * @return
     */
    public static boolean verify(String token, String secretKey) {
        String secret = getClaim(token, SecurityConstant.USER_ID) + secretKey;
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        verifier.verify(token);
        return true;
    }

    /**
     * 获得Token中的信息无需secret解密也能获得
     * @param token
     * @param claim
     * @return
     */
    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名
     * @param userId
     * @return
     */
    public static String sign(String userId, String userName, String secretKey) {
        // 帐号加JWT私钥加密
        String secret = userId + secretKey;
        Algorithm algorithm = Algorithm.HMAC256(secret);

        return JWT.create()
                .withClaim(SecurityConstant.USER_ID, userId)
                .withClaim(SecurityConstant.USER_NAME, userName)
                .sign(algorithm);
    }
}
